package com.example.huadu_server.websocket;

import com.example.huadu_server.websocket.service.ChatService;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.TextMessage;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketServer extends TextWebSocketHandler {

    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Autowired
    private ChatService chatService;

    // 连接建立后的回调
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = session.getUri().getPath().split("/")[2];
        String landlordId = session.getUri().getPath().split("/")[3];

        // 根据连接 URL 的顺序，构造存储的 key
        // 用户端连接时 key 为 "userId-landlordId"
        // 房东端连接时 key 为 "landlordId-userId"
        String sessionKey = session.getUri().getPath().split("/")[2] + "-" + session.getUri().getPath().split("/")[3];
        sessions.put(sessionKey, session);

        System.out.println("WebSocket连接已建立，存储键名：" + sessionKey);
    }


    // 处理接收到的消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JSONObject jsonMessage = JSONObject.parseObject(message.getPayload());
        String senderId = jsonMessage.getString("senderId");
        String receiverId = jsonMessage.getString("receiverId");
        String content = jsonMessage.getString("content");
        Integer houseId = jsonMessage.getInteger("houseId");
        Integer conversationId = jsonMessage.getInteger("conversationId");

        // 构造发送给接收方的 JSON 数据
        JSONObject sendJson = new JSONObject();
        sendJson.put("senderId", senderId);
        sendJson.put("receiverId", receiverId);
        sendJson.put("content", content);
        sendJson.put("houseId", houseId);
        sendJson.put("conversationId", conversationId);

        // 推送消息给接收方
        String receiverKey = receiverId + "-" + senderId;  // 反向推送给对方

        System.out.println("生成的接收方键名：" + receiverKey);
        WebSocketSession receiverSession = sessions.get(receiverKey);

        if (receiverSession != null && receiverSession.isOpen()) {
            System.out.println("找到接收方会话，发送消息...");
            System.out.println("发送消息给：" + receiverSession.getId());
            receiverSession.sendMessage(new TextMessage(sendJson.toJSONString()));// 发送消息
        } else {
            System.out.println("未找到接收方会话，或者会话未打开。");
        }
    }

    // 静态方法：根据传入的两个 ID 构造 key 并推送消息
    public static void sendMessageToTarget(Integer firstId, Integer secondId, String payload) {
        // 构造 key：直接按照 firstId + "-" + secondId 拼接
        String key = firstId + "-" + secondId;
        WebSocketSession session = sessions.get(key);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(payload));
                System.out.println("成功向 key = " + key + " 推送消息: " + payload);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("未找到 key = " + key + " 对应的 WebSocketSession");
        }
    }

    // 连接关闭后的回调
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = session.getUri().getPath().split("/")[2];
        String landlordId = session.getUri().getPath().split("/")[3];
        String sessionKey = userId + "-" + landlordId;
        sessions.remove(sessionKey);
        System.out.println("WebSocket连接已关闭，移除键名：" + sessionKey);
    }
}
